﻿using System.Net.Http;

namespace HttpClientLite.Extensions;

/// <summary>
/// MultipartFormDataContent扩展函数
/// </summary>
public static class MultipartFormDataContentExtensions
{
    /// <summary>
    /// 添加参数数据
    /// </summary>
    /// <param name="formDataContent"></param>
    /// <param name="name"></param>
    /// <param name="value"></param>
    public static void AddParameter(this MultipartFormDataContent formDataContent, string name, string value)
    {
        var dataContent = new StringContent(value);
        formDataContent.Add(dataContent, name);
    }

    /// <summary>
    /// 添加参数数据
    /// </summary>
    /// <param name="formDataContent"></param>
    /// <param name="name"></param>
    /// <param name="value"></param>
    public static void AddParameter(this MultipartFormDataContent formDataContent, string name, byte[] value)
    {
        var dataContent = new ByteArrayContent(value);
        formDataContent.Add(dataContent, name);
    }

    /// <summary>
    /// 添加文件参数数据
    /// </summary>
    /// <param name="formDataContent"></param>
    /// <param name="name"></param>
    /// <param name="fileName"></param>
    /// <param name="value"></param>
    public static void AddFile(this MultipartFormDataContent formDataContent, string name, string fileName, byte[] value)
    {
        var dataContent = new ByteArrayContent(value);
        formDataContent.Add(dataContent, name, fileName);
    }

    /// <summary>
    /// 添加文件参数数据
    /// </summary>
    /// <param name="formDataContent"></param>
    /// <param name="name"></param>
    /// <param name="fileName"></param>
    /// <param name="fileStream"></param>
    public static void AddFile(this MultipartFormDataContent formDataContent, string name, string fileName, Stream fileStream)
    {
        var dataContent = new ByteArrayContent(StreamToByteArray(fileStream));
        formDataContent.Add(dataContent, name, fileName);
    }

    /// <summary>
    /// 添加文件参数数据
    /// </summary>
    /// <param name="formDataContent"></param>
    /// <param name="name"></param>
    /// <param name="fileName"></param>
    /// <param name="filePath"></param>
    public static void AddFile(this MultipartFormDataContent formDataContent, string name, string fileName, string filePath)
    {
        var dataContent = new ByteArrayContent(File.ReadAllBytes(filePath));
        formDataContent.Add(dataContent, name, fileName);
    }

    private static byte[] StreamToByteArray(Stream inputStream)
    {
        using (var memoryStream = new MemoryStream())
        {
            inputStream.CopyTo(memoryStream);
            return memoryStream.ToArray();
        }
    }
}